define(['jquery', 'mustache'], function($, mustache) {
  var that = {};
  var $node, $tplNode;
  var $title;
  var $tpl, data, callback;
  var baseUrl = '../template/modal/base.html';

  var onClick = function() {
    $node.bind('click', function() {
      $tplNode.modal('toggle');
      // $tplNode.modal('loaded.bs.modal', function(e) {
      //
      // });
    });
  };

  // 渲染 modal 的数据
  var renderData = function(url, data) {
    $.get(url)
    .then(function(ret) {
      var $tpl = mustache.render(ret, data);
      $tplNode.find('.modal-body').append($tpl);
    });
  };

  // 加载 modal 模版
  var initTPL = function() {
    // console.log(tplPath);
    $tplNode.modal({
      show: false,
      remote: baseUrl
    });
  };

  var initPlugins = function(tpl, data, config) {
    that.initTPL(tpl);
    that.onClick();
    $title = config.title;
    $tplNode.on('show.bs.modal', function(e) {
      console.log('show.bs.modal');
      $tplNode.find('.modal-title').text($title);
      that.renderData(config.tplUrl, data);
    });

    $tplNode.on('hide.bs.modal', function(e) {
      console.log('hide.bs.modal');
    });

    $tplNode.on('shown.bs.modal', function(e) {
      console.log('shown.bs.modal');

    });

    $tplNode.on('loaded.bs.modal', function(e) {
      console.log('loaded.bs.modal');
    });
  };

  var parseDOM = function(node, tplNode) {
    $node = $(node);
    $tplNode = $(tplNode);
  };

  var bindListener = function() {
    that.renderData = renderData;
    that.initTPL = initTPL;
    that.onClick = onClick;
  };

  var init = function(config) {
    parseDOM(config.node, config.tplNode);
    bindListener();
    initPlugins(config.url, config.data, config);
  };

  // that.modalClick = modalClick;
  that.init = init;
  return that;
});
